package com.xzsoft.gdwz.schedual;

import java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.suning.api.DefaultSuningClient;
import com.suning.api.entity.govbus.MessageDeleteRequest;
import com.suning.api.entity.govbus.MessageDeleteResponse;
import com.suning.api.entity.govbus.MessageGetRequest;
import com.suning.api.entity.govbus.MessageGetResponse;
import com.suning.api.entity.govbus.OrderDetailGetRequest;
import com.suning.api.entity.govbus.OrderDetailGetResponse;
import com.suning.api.exception.SuningApiException;
import com.xzsoft.gdwz.model.TrdPsEmInfLog;
import com.xzsoft.gdwz.model.UserToken;
import com.xzsoft.gdwz.services.OrderSchedual;
import com.xzsoft.gdwz.services.RefreshTokenServices;
import com.xzsoft.gdwz.services.SnOrderService;
import com.xzsoft.gdwz.services.TrdPsEmInfLogService;

/**
 * 
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company:兴竹信息
 * </p>
 * 
 * @author:张亚
 * @date:2016-9-7 下午2:16:28
 */
@Component("snOrderSchedual")
public class SNOrderSchedualImpl implements OrderSchedual {
	@Autowired
	private RefreshTokenServices refreshTokenServices;
	@Autowired
	private SnOrderService snOrderService;
	@Autowired
	private TrdPsEmInfLogService trdPsEmInfLogService;
	Logger logger = Logger.getLogger(SNOrderSchedualImpl.class);

	@Scheduled(cron = "0 5/10 * * * ?")
	@Override
	public void getOrderInf() {
		String msgId = "";
		JSONObject OrderDetail = null;
		String orderId = "";
		UserToken userToken = refreshTokenServices.getToken("SN");
		String appKey = userToken.getUsername();
		String appSecret = userToken.getPassword();
		String serverUrl = userToken.getOrderIdUrl();
		logger.info("appKey:"+appKey+"  appSecret:"+appSecret+"  serverUrl"+serverUrl);
		
		// 获取消息信息客户端对象orderIdUrlClient
		MessageGetRequest messageGetRequest = new MessageGetRequest();
		messageGetRequest.setType("11");
		messageGetRequest.setCheckParam(true);// api入参校验逻辑开关，当测试稳定之后建议设置为 false
												// 或者删除该行
		DefaultSuningClient messageGetClient = new DefaultSuningClient(
				serverUrl, appKey, appSecret, "json");
		
		// 获取订单详情信息客户端对象orderGetClient
		OrderDetailGetRequest orderDetailGetRequest = new OrderDetailGetRequest();
		orderDetailGetRequest.setCheckParam(true);
		DefaultSuningClient orderDetailGetClient = new DefaultSuningClient(
				serverUrl, appKey, appSecret, "json");
		// 删除消息信息客户端对象messageDeleteClient
		
		MessageDeleteRequest messageDeleteRequest = new MessageDeleteRequest();
		messageDeleteRequest.setCheckParam(true);
		DefaultSuningClient messageDeleteClient = new DefaultSuningClient(
				serverUrl, appKey, appSecret, "json");
		JSONArray orderIdArray = null;

		// 获取消息
		try {
			MessageGetResponse messageGetResponse = messageGetClient
					.excute(messageGetRequest);
			logger.info("获取消息返回的json格式数据 :" + messageGetResponse.getBody());
			JSONObject jb = JSONObject.fromObject(messageGetResponse.getBody());
			JSONObject sn_body = (JSONObject) jb.get("sn_responseContent");

			if (sn_body.containsKey("sn_error")) {
				JSONObject sn_error = (JSONObject) sn_body.get("sn_error");
				logger.info("获取消息失败！返回错误信息：" + sn_error.toString());
				throw new Exception("获取消息失败！返回错误信息：" + sn_error.toString());
			} else {
				JSONObject getMessage = (JSONObject) sn_body.get("sn_body");
				JSONObject resultInfo = (JSONObject) getMessage
						.get("getMessage");
				orderIdArray = (JSONArray) resultInfo.get("resultInfo");
				logger.info("订单消息数组：" + orderIdArray.toString());
			
				// 获取订单并保存
				try {
					for (Object object : orderIdArray) {
						msgId = JSONObject.fromObject(object).get("id") + "";
						orderId =(String) JSONObject.fromObject(object).get("orderNo");
						logger.info(orderId);
						orderDetailGetRequest.setOrderId(orderId);
						OrderDetailGetResponse orderDetailGetResponse = orderDetailGetClient
								.excute(orderDetailGetRequest);
						logger.info("获取订单返回json/xml格式数据 :"
								+ orderDetailGetResponse.getBody());
						JSONObject orderJb = JSONObject
								.fromObject(orderDetailGetResponse.getBody());
						JSONObject orderContent = (JSONObject) orderJb
								.get("sn_responseContent");
						if (orderContent.containsKey("sn_error")) {
							JSONObject sn_error = (JSONObject) orderContent
									.get("sn_error");
							logger.info("获取订单失败！返回错误信息：" + sn_error.toString());
							throw new Exception("获取订单失败！返回错误信息："
									+ sn_error.toString());
		 
						} else {
							JSONObject getOrderDetail = (JSONObject) orderContent
									.get("sn_body");
							OrderDetail = (JSONObject) getOrderDetail
									.get("getOrderDetail");
							orderId = OrderDetail.getString("orderId");
							snOrderService.saveOrder(OrderDetail);
							
							// 删除订单消息
							try {
								logger.info(msgId);
								messageDeleteRequest.setId(msgId);
								MessageDeleteResponse messageDeleteResponse = messageDeleteClient
										.excute(messageDeleteRequest);
								logger.info("删除消息返回json/xml格式数据 :"
										+ messageDeleteResponse.getBody());
								msgId = "";

							} catch (Exception e) {
								e.printStackTrace();
								TrdPsEmInfLog log = new TrdPsEmInfLog();
								log.setId(UUID.randomUUID().toString());
								log.setEmName("SN");
								log.setErrorMsg(e.getMessage());
								logger.info(e.getMessage());
								log.setHasRecieve("0");
								trdPsEmInfLogService.insertTrdPsEmInfLog(log);
								log = null;
							}
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
					TrdPsEmInfLog log = new TrdPsEmInfLog();
					log.setId(UUID.randomUUID().toString());
					log.setEmName("SN");
					log.setErrorMsg(e.getMessage());
					logger.info(e.getMessage());
					log.setHasRecieve("0");
					log.setOrderId(orderId);
					if(OrderDetail != null){
					log.setOrderInfo(OrderDetail.toString());
					}
					trdPsEmInfLogService.insertTrdPsEmInfLog(log);
					log = null;
				}
			
			}
		} catch (Exception e) {
			e.printStackTrace();
			TrdPsEmInfLog log = new TrdPsEmInfLog();
			log.setId(UUID.randomUUID().toString());
			log.setEmName("SN");
			log.setErrorMsg(e.getMessage());
			logger.info(e.getMessage());
			log.setHasRecieve("0");
			trdPsEmInfLogService.insertTrdPsEmInfLog(log);
			log = null;
		}
		
		
	}
}